
class PasswordResetController < ApplicationController
  before_filter :require_no_logined
  before_filter :validate_sms_code, :only => [:create]
  after_filter :inc_ip_count, :only => :create

  helper_method :require_recaptcha?

  layout 'auth', only: [:new]

  def new
    @user = User.new

    set_seo_meta("忘记密码")
  end

  def create
    #@user = User.find_by(:password_reset_token => params[:id])
    @user = User.find_by(:mobile => params[:user][:mobile])
    if @user
      @user.in_password_reset = true
      @user.password_reset_token_sent_at = Time.now
      if @user.update_attributes params.require(:user).permit(:sms_code, :password, :password_confirmation)
        flash[:success] = "密码重置成功, 请登录"
        redirect_to sign_in_path
      else
        flash[:error] = "密码重置失败"
        redirect_to :back
      end
    else
      flash[:error] = "未找到该手机号注册的用户"
      redirect_to :back
    end
  end

  #def edit
    #@user = User.where(:password_reset_token => params[:id]).first

    #if @user && @user.password_reset_token_sent_at > 2.hours.ago
      #@user.in_password_reset = true
      #render :edit
    #else
      #flash[:error] = "密码重置的令牌不存在或已过期"
      #redirect_to new_password_reset_url
    #end
  #end

  #def update
  #end

  private

  def validate_sms_code
    unless params[:user][:sms_code].present? && (params[:user][:sms_code] == Rails.cache.read(params[:user][:mobile]).to_s)
      flash[:error] = '手机验证码不正确'
      redirect_to :back
    end
  end

  def inc_ip_count
    Rails.cache.write "password_reset_count/#{request.remote_ip}", ip_count + 1, :expires_in => 60.seconds
  end

  def ip_count
    Rails.cache.read("password_reset_count/#{request.remote_ip}").to_i
  end

  def require_recaptcha?
    ip_count >= 3
  end
end
